/**
 * 诊断工具函数，用于调试和诊断登录和用户信息问题
 */

import { useUserStore } from "@/stores/user";

/**
 * 检查登录状态
 * @returns 登录状态诊断信息
 */
export function checkLoginState() {
  console.group('===== 登录状态诊断 =====');
  
  // 检查localStorage
  const accessToken = localStorage.getItem('accessToken');
  const refreshToken = localStorage.getItem('refreshToken');
  const userInfoStr = localStorage.getItem('userInfo');
  const isLoggedInFlag = localStorage.getItem('isLoggedIn');
  
  console.log('LocalStorage状态:');
  console.log('- accessToken存在:', !!accessToken);
  console.log('- refreshToken存在:', !!refreshToken);
  console.log('- userInfo存在:', !!userInfoStr);
  console.log('- isLoggedIn标志:', isLoggedInFlag);
  
  // 检查token格式
  if (accessToken) {
    console.log('Token格式检查:');
    console.log('- 长度:', accessToken.length);
    console.log('- 以Bearer开头:', accessToken.startsWith('Bearer '));
    console.log('- 示例片段:', `${accessToken.substring(0, 10)}...`);
  }
  
  // 检查用户信息格式
  let userInfo = null;
  if (userInfoStr) {
    try {
      userInfo = JSON.parse(userInfoStr);
      console.log('用户信息检查:');
      console.log('- 用户ID:', userInfo.id, `(类型: ${typeof userInfo.id})`);
      console.log('- 用户名:', userInfo.username);
      if (userInfo.title) {
        console.log('- 标签类型:', typeof userInfo.title);
        if (typeof userInfo.title === 'string') {
          console.log('- 标签值:', userInfo.title);
        } else {
          console.log('- 标签数量:', userInfo.title.length);
        }
      }
    } catch (e) {
      console.error('解析用户信息失败:', e);
    }
  }
  
  // 检查Pinia存储状态
  const userStore = useUserStore();
  console.log('Pinia Store状态:');
  console.log('- isLoggedIn:', userStore.isLoggedIn);
  console.log('- userInfo存在:', !!userStore.userInfo);
  console.log('- accessToken长度:', userStore.accessToken?.length || 0);
  
  if (userStore.userInfo) {
    const storeUserInfo = userStore.userInfo;
    console.log('- 用户ID:', storeUserInfo.id, `(类型: ${typeof storeUserInfo.id})`);
    console.log('- 用户名:', storeUserInfo.username);
  }
  
  // 检查本地存储和Pinia是否一致
  if (userInfo && userStore.userInfo) {
    console.log('一致性检查:');
    console.log('- 用户ID一致:', userInfo.id == userStore.userInfo.id); // 用==而不是===，允许类型不同
    console.log('- 用户名一致:', userInfo.username === userStore.userInfo.username);
  }
  
  console.groupEnd();
  
  return {
    localStorage: {
      hasToken: !!accessToken,
      hasRefreshToken: !!refreshToken,
      hasUserInfo: !!userInfoStr,
      isLoggedInFlag
    },
    userInfo: userInfo ? {
      id: userInfo.id,
      username: userInfo.username
    } : null,
    storeState: {
      isLoggedIn: userStore.isLoggedIn,
      hasUserInfo: !!userStore.userInfo,
      hasToken: !!userStore.accessToken
    }
  };
}

/**
 * 测试API请求是否包含正确的认证头
 * @param url API地址
 * @returns 请求结果
 */
export async function testApiAuth(url: string = '/api/user/check') {
  console.group('===== API认证测试 =====');
  
  const token = localStorage.getItem('accessToken');
  console.log('准备进行API测试:');
  console.log('- URL:', url);
  console.log('- 令牌存在:', !!token);
  
  if (token) {
    // 格式化token
    const authHeader = token.startsWith('Bearer ') ? token : `Bearer ${token}`;
    console.log('- 认证头:', authHeader.substring(0, 15) + '...');
    
    try {
      const startTime = Date.now();
      const response = await fetch(url, {
        headers: {
          'Authorization': authHeader
        }
      });
      const endTime = Date.now();
      
      console.log('请求结果:');
      console.log('- 状态码:', response.status);
      console.log('- 耗时:', endTime - startTime, 'ms');
      
      if (response.ok) {
        try {
          const data = await response.json();
          console.log('- 响应数据:', data);
          console.groupEnd();
          return { success: true, status: response.status, data };
        } catch (e) {
          console.log('- 响应不是JSON格式');
          const text = await response.text();
          console.log('- 响应文本:', text.substring(0, 100) + (text.length > 100 ? '...' : ''));
          console.groupEnd();
          return { success: false, status: response.status, error: 'Invalid JSON', text };
        }
      } else {
        console.log('- 请求失败');
        console.groupEnd();
        return { success: false, status: response.status };
      }
    } catch (error) {
      console.error('- 请求发生错误:', error);
      console.groupEnd();
      return { success: false, error };
    }
  } else {
    console.log('- 没有令牌，无法进行测试');
    console.groupEnd();
    return { success: false, error: 'No token' };
  }
}

/**
 * 清理登录状态
 * @param logout 是否调用store的logout方法
 */
export function clearLoginState(logout: boolean = true) {
  console.group('===== 清理登录状态 =====');
  
  // 清理localStorage
  console.log('清理localStorage:');
  localStorage.removeItem('accessToken');
  localStorage.removeItem('refreshToken');
  localStorage.removeItem('userInfo');
  localStorage.removeItem('isLoggedIn');
  console.log('- 已清理所有登录相关的localStorage项目');
  
  // 清理store状态
  if (logout) {
    const userStore = useUserStore();
    console.log('清理Pinia Store:');
    userStore.logout();
    console.log('- 已调用logout()方法清理store状态');
  }
  
  console.log('清理完成');
  console.groupEnd();
  
  return { success: true };
}

/**
 * 测试登录API，直接调用不通过store
 * @param username 用户名
 * @param password 密码
 * @returns 登录结果
 */
export async function testLogin(username: string, password: string) {
  console.group('===== 登录API测试 =====');
  
  try {
    console.log(`准备使用凭据登录: 用户名=${username}, 密码=${password.substring(0, 1)}***`);
    
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/auth/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username,
        password,
        rememberMe: true
      })
    });
    
    console.log('登录响应状态:', response.status);
    
    const jsonResponse = await response.json();
    console.log('登录响应完整内容:', jsonResponse);
    
    if (jsonResponse.data && jsonResponse.data.accessToken) {
      console.log('成功获取令牌信息:');
      console.log('- accessToken:', jsonResponse.data.accessToken.substring(0, 10) + '...');
      console.log('- userId:', jsonResponse.data.userId);
      console.log('- username:', jsonResponse.data.username);
    } else {
      console.error('未能获取有效的令牌信息');
    }
    
    console.groupEnd();
    return {
      success: response.ok && jsonResponse.code === 200,
      response: jsonResponse
    };
  } catch (error) {
    console.error('登录请求失败:', error);
    console.groupEnd();
    return {
      success: false,
      error
    };
  }
}

/**
 * 显示当前用户权限信息
 * 用于诊断当前用户的角色和权限状态
 * @returns {object} 用户权限信息
 */
export function showUserPermissionInfo() {
  try {
    // 从localStorage获取当前用户信息
    const userInfoStr = localStorage.getItem('userInfo');
    if (!userInfoStr) {
      console.error('未找到用户信息，请先登录');
      return { success: false, error: '未找到用户信息' };
    }

    // 解析用户信息
    const userInfo = JSON.parse(userInfoStr);
    
    // 检查用户是否有管理员权限
    const role = userInfo.role || '';
    const isAdmin = 
      role === 'ROLE_ADMIN' || 
      role === 'ROLE_SUPER_ADMIN' ||
      role.toLowerCase().includes('admin') || 
      role.toLowerCase().includes('super');
    
    // 打印用户权限信息
    console.group('===== 用户权限信息 =====');
    console.log('用户名:', userInfo.username);
    console.log('用户ID:', userInfo.id);
    console.log('角色代码:', role);
    console.log('是否具有管理员权限:', isAdmin);
    console.log('可访问管理页面:', isAdmin ? '是' : '否');
    console.groupEnd();
    
    return {
      success: true,
      username: userInfo.username,
      userId: userInfo.id,
      role: role,
      isAdmin: isAdmin,
      canAccessAdmin: isAdmin
    };
  } catch (error) {
    console.error('获取用户权限信息失败:', error);
    return { success: false, error };
  }
}

export default {
  checkLoginState,
  testApiAuth,
  clearLoginState,
  testLogin,
  showUserPermissionInfo
}; 